package callers.plm;

import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PLMMessageFormatter
{
    public static String formatMessage(String inputText, Map<Pattern, String> raplacementMap) {

        inputText = replaceValue(inputText,raplacementMap);
        String retVal = "A" + String.format("%05d", inputText.length()) + inputText;
        
        System.out.println(retVal);
        return retVal;
    }

    private static String replaceValue(String inputText, Map<Pattern, String> replacementMap) {

        Set<Pattern> patterns = replacementMap.keySet();
        for (Pattern pattern : patterns) {
            Matcher matcher = pattern.matcher(inputText);
            if (matcher.find()) {
                String textToReplacement = matcher.group(1);
                String replacement = replacementMap.get(pattern);
                inputText = inputText.replaceAll(textToReplacement, replacement);
            }
        }
        return inputText;
    }
    
    public static String removeParameter(String xml, String parameter){
    	String REGEXTEMPLATE_DESIGNERQUERYPARAMETERVALUE = "\\<\\s*p\\s*n\\=\"" + parameter + "\"\\s*\\>(.*?)\\<\\s*\\/p\\s*\\>"; 

    	Pattern pattern = Pattern.compile(REGEXTEMPLATE_DESIGNERQUERYPARAMETERVALUE, Pattern.DOTALL);
    	Matcher matcher = pattern.matcher(xml);
    	if (matcher.find()) {
    		xml = xml.replace(matcher.group(), "");
    	}
    	return xml;
    }
    
    public static String changeParameterValue(String xml, String parameter, String newValue){
    	String REGEXTEMPLATE_DESIGNERQUERYPARAMETERVALUE = "\\<\\s*p\\s*n\\=\"" + parameter + "\"\\s*\\>(.*?)\\<\\s*\\/p\\s*\\>"; 

    	Pattern pattern = Pattern.compile(REGEXTEMPLATE_DESIGNERQUERYPARAMETERVALUE, Pattern.DOTALL);
    	Matcher matcher = pattern.matcher(xml);
    	if (matcher.find()) {
    		xml = xml.replace(matcher.group(1), newValue);
    	}
    	return xml;
    }
    
    public static String changeHeaderValue(String xml, String headerParameter, String newValue){
    	String REGEXTEMPLATE_DESIGNERQUERYPARAMETERVALUE = "\\<" + headerParameter + "\\>(.*?)\\<\\/" + headerParameter + "\\>"; 

    	Pattern pattern = Pattern.compile(REGEXTEMPLATE_DESIGNERQUERYPARAMETERVALUE, Pattern.DOTALL);
    	Matcher matcher = pattern.matcher(xml);
    	if (matcher.find()) {
    		xml = xml.replace(matcher.group(1), newValue);
    	}
    	return xml;
    }
}
